<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class CateController extends Controller
{
    //add
    public function add()
    {
    	$title = '分类添加';

    	//查询分类
    	$data = DB::table('cate')
    	-> select('*',DB::raw("concat(path,',',id) as sort_str"))
    	-> orderBy('sort_str','asc')
    	-> get();
    	foreach($data as $k => $v){
    		//拆分数组
    		$arr = explode(',',$v->path);
    		//统计数组的元素个数
    		$num = count($arr);
    		//重复字符串
    		$str = str_repeat('----/',$num);
    		//修改name名称
    		$data[$k] -> name = $str.$v -> name;
    	}
    	//dd($data);
    	return view('admin.cate.add',['title' => $title,'data' => $data]);
    }
    //insert
    public function insert(Request $request)
    {
    	// dd($request -> all());
    	$data = $request -> except('_token');

    	if($data['pid']==0)
    	{
	    	//处理path字段
	    	$data['path'] = 0;

	    	//添加数据
	    	$res = DB::table('cate') -> insert($data);

	    	if($res){
	    		return redirect('/admin/cate/index') -> with(['success' => '添加成功']);
	    	}else
	    	{
	    		return back() -> with(['error' => '添加失败']);
	    	}
    	}
    	else
    	{
	    	//处理path字段
	    	$parentPath = DB::table('cate') -> where('id','=',$data['pid']) -> first() -> path;
	    	// echo $parentPath;
	    	$data['path'] = $parentPath.','.$data['pid'];

	    	//添加数据
	    	$res = DB::table('cate') -> insert($data);

	    	if($res){
	    		return redirect('/admin/cate/index') -> with(['success' => '添加成功']);
	    	}else
	    	{
	    		return back() -> with(['error' => '添加失败']);
	    	}
    	}

    	

    }

    //index
    public function index()
    {
    	$title = '分类列表';
    	//获取所有分类
    	// $data = DB::table('cate')
    	// -> select('*',DB::raw("concat(path,',',id) as sort_str"))
    	// -> orderBy('sort_str','asc')
    	// -> get();
    	//select c1.*,concat(c1.path,',',c1.id) as sort_str,c2.name as p_name from p_cate as c1 LEFT JOIN p_cate as c2 on c1.pid = c2.id order by sort_str ASC
    	$data = DB::table('cate as c1')
    	-> leftJoin('cate as c2','c1.pid','=','c2.id')
    	-> select('c1.*',DB::raw("concat(c1.path,',',c1.id) as sort_str"),'c2.name as p_name')
    	-> orderBy('sort_str','asc')
    	-> paginate(2000);

    	foreach ($data as $k => $v) {
    		if(empty($v -> p_name))
    		{
    			$data[$k] -> p_name = '--';
    		}

    		//拆分数组
    		$arr = explode(',',$v->path);
    		//统计数组的元素个数
    		$num = count($arr) - 1;
    		//重复字符串
    		$str = str_repeat('----/',$num);
    		//修改name名称
    		$data[$k] -> name = $str.$v -> name;
    	}

    	return view('admin.cate.index',['title' => $title,'data' => $data]);
    }


    //edit
    public function edit($id)
    {

    	$title = '分类编辑';
    	//获取分类
    	$data = DB::table('cate') -> where('id','=',$id) -> first();
    	// $allData = DB::table('cate') -> get();
    	$allData = DB::table('cate')
    	-> select('*',DB::raw("concat(path,',',id) as sort_str"))
    	-> orderBy('sort_str','asc')
    	-> get();


    	foreach($allData as $k => $v){
    		//拆分数组
    		$arr = explode(',',$v->path);
    		//统计数组的元素个数
    		$num = count($arr);
    		//重复字符串
    		$str = str_repeat('----/',$num);
    		//修改name名称
    		$allData[$k] -> name = $str.$v -> name;
    	}
    	return view('admin.cate.edit',['title'=>$title,'data'=>$data,'allData' => $allData]);
    	
    }

    //update
    public function update(Request $request)
    {
    	// dd($request -> all());
    	$data = $request -> except('_token');
        // dd($data);
        if($data['pid']==0)
        {
            $res = DB::table('cate')->where('id',$data['id'])->update($data);
        }
        else
        {
            //处理path字段
            //获得父类的path
            $parentPath = DB::table('cate') -> where('id','=',$data['pid']) -> first() -> path;
            // echo $parentPath;
            //利用父类的path拼接自己的path
            $data['path'] = $parentPath.','.$data['pid'];

            $res = DB::table('cate') -> where('id','=',$data['id']) -> update($data);
        }

    	
        //判断更新是否成功
    	if($res)
    	{
    		return redirect('/admin/cate/index') -> with(['success' => '更新成功']);
    	}else
    	{
    		return back() -> with(['error' => '更新失败']);
    	}
    }

    //delete
    public function delete($id)
    {
    	$title = '分类删除';
    	$data = DB::table('cate') -> where('pid','=',$id) -> get();

    	if($data)
    	{
    		return back() -> with(['info' => '对不起,下面有子分类,不能删除']);
    	}else
    	{
    		$res = DB::table('cate') -> where('id','=',$id) -> delete();
    		if($res)
    		{
    			return redirect('admin/cate/index') -> with(['success' => '删除成功']);
    		}else
    		{
    			return back() -> with(['info' => '删除失败']);
    		}
    	}
    }

    //递归查询
    public function getCatesPid($pid)
    {
    	$data = DB::table('cate') -> where('pid','=',$pid) -> get();
    	$arr = [];
    	foreach ($data as $k => $v) {
    		$v -> sub = $this -> getCatesPid($v -> id);
    		$arr[] = $v;
    	}

    	return $arr;
    	// dd($data);
    }

    public function test()
    {
    	dd($this -> getCatesPid(0));
    }

    //优化过的递归函数
    public function getCates()
    {
    	$data = DB::table('cate') -> get();
    	return $data;
    }

    public function getCatesArrPid($arr,$pid)
    {
    	$data = [];
    	foreach ($arr as $k => $v) {
    		if($pid == $v -> pid)
    		{
    			$v -> sub = $this -> getCatesArrPid($arr,$v->id);
    			$data[] = $v;
    		}
    	}

    	return $data;
    }

    public function mytest()
    {
    	$arr = $this -> getCates();
    	dd($this -> getCatesArrPid($arr,0));
    }
}
